package com.turing.common.util.uncompress;


import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;

import java.io.*;
import java.util.logging.Logger;

public class SevenZipUncompress extends AbstractUncompress {

    private static final Logger logger = Logger.getLogger(SevenZipUncompress.class.getName());

    /**
     * 解压 7z 文件 
     * @param inputFile 7z 文件路径
     * @param destDirPath 解压目标目录
     * @return
     */
    @Override
    public void uncompress(String inputFile, String destDirPath) {

        /**
         * zip解压
         * @param inputFile 待解压文件名
         * @param destDirPath  解压路径
         */
        File srcFile = new File(inputFile);//获取当前压缩文件
        // 判断源文件是否存在
        if (!srcFile.exists()) {
            logger.warning(srcFile.getPath() + "所指文件不存在");
        }
        //开始解压
        SevenZFile zIn = null;
        SevenZArchiveEntry entry = null;
        File file = null;
        try {
            zIn = new SevenZFile(srcFile);
            while ((entry = zIn.getNextEntry()) != null) {
                if (!entry.isDirectory()) {
                    file = new File(destDirPath, entry.getName());
                    if (!file.exists()) {
                        new File(file.getParent()).mkdirs();//创建此文件的上级目录
                    }
                    OutputStream out = new FileOutputStream(file);
                    BufferedOutputStream bos = new BufferedOutputStream(out);
                    int len = -1;
                    byte[] buf = new byte[1024];
                    while ((len = zIn.read(buf)) != -1) {
                        bos.write(buf, 0, len);
                    }
                    // 关流顺序，先打开的后关闭
                    bos.close();
                    out.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /*public static void main(String[] args) throws IOException {

        try {
            long l = System.currentTimeMillis();
            uncompress("D:\\图灵.7z","D:\\图灵");
            long l2 = System.currentTimeMillis();
            System.out.println(l2-l);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }*/

}